package com.azzcs.parse;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Author: wzg
 * @Date: 2020/12/6 上午11:15
 */
public class XMLConfigurationBuilder {
    private Configuration configuration;
    public XMLConfigurationBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseConfiguration(InputStream input) throws Exception {
        Document document = new SAXReader().read(input);
        Element configurationElement = document.getRootElement();
        List<Element> list = configurationElement.selectNodes("//property");
        Properties properties = new Properties();
        list.forEach(property->{
            properties.setProperty(property.attributeValue("name"),property.attributeValue("value"));
        });
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driver"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("user"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);

        List<Element> mappers = configurationElement.selectNodes("//mapper");

        XMLMapperStatementBuilder xmlMapperStatementBuilder = new XMLMapperStatementBuilder(configuration);

        for (Element mapper:mappers) {
            InputStream mapperInput = Resource.getResourceAsStream(mapper.attributeValue("resource"));
            xmlMapperStatementBuilder.parse(mapperInput);
        }

    }
}
